package com.earthea.chatbot.login.common.util;

import com.earthea.chatbot.common.entity.HttpCodeEnum;
import com.earthea.chatbot.common.exception.ServiceException;
import com.earthea.chatbot.domain.LoginUser;
import com.earthea.chatbot.login.common.constant.Constants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全服务工具类
 */
public class SecurityUtils {

    /**
     * 获取用户
     */
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException(HttpCodeEnum.HTTP_UNAUTHORIZED, "获取用户信息异常");
        }
    }

    /**
     * 获取用户ID
     */
    public static Long getLoginUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && Constants.ADMIN_USER_ID == userId;
    }

}
